import _ from 'lodash'
import { useSelector } from 'react-redux'
import { Link } from 'react-router-dom'

import { routes } from '@/router'
import { useRouterInfo } from '@/hooks/routetHook'

import type { RouteObject } from 'react-router-dom'
import type { MenuProps } from 'antd'
import type { RootState } from '@/store'


export const useMenuData = () => {

    type MenuItem = Required<MenuProps>['items'][number]

    const { match } = useRouterInfo()

    const [ matchFirst, matchSecond ] = match!

    const currentPath = matchFirst.pathnameBase // 当期路由
    const currentSubPath = matchSecond.pathnameBase // 当前子路由

    console.log('当期路由', currentPath)
    console.log('当前子路由', currentSubPath)

    const permission = useSelector((state: RootState) => state.userStore.infos.permission) || []

    const routesFilter: (x: RouteObject[]) => RouteObject[] = (row) => {

        const routerMenus: RouteObject[] = []

        row.forEach(item => {
            const routeRaw: RouteObject = {
                path: item.path,
                meta: item.meta ?? {},
                children: []
            }

            if (!routeRaw.meta?.menu) {
                return
            }
            if (!permission.includes(routeRaw.meta?.auth as string)) {
                return
            }

            routerMenus.push(routeRaw)

            if (item.children && item.children.length) {
                routeRaw.children = routesFilter(item.children)
            }

        })
        return routerMenus
    }

    const menuDataReset: (x: RouteObject[], y?: string) => MenuProps['items'] = (row, path) => {
        const target: MenuItem[] = []
        row.forEach((item) => {
            if (!item.meta) return false

            const { title, icon } = item.meta
            const temp: MenuItem = {
                label: (<Link to={item.path as string}>{title}</Link>),
                key: path ? `${path}${item.path}` : item.path || '/',
                icon
            }

            if (item.children && item.children.length) {
                // @ts-ignore
                temp.children = menuDataReset(item.children, item.path)
            }
            target.push(temp)
        })

        return target
    }


    const menuList = menuDataReset(routesFilter(_.cloneDeep(routes)))

    return { currentPath, currentSubPath, menuList }
}